package com.xxp.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xxp.controller.request.BookRequest;
import com.xxp.entity.Book;
import com.xxp.entity.Category;
import com.xxp.mapper.BookMapper;
import com.xxp.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;
    @Override
    public Object listByCondition(BookRequest bookRequest) {
        PageHelper.startPage(bookRequest.getPageNum(),bookRequest.getPageSize());
        List<Book> books = bookMapper.listByCondition(bookRequest);
        return new PageInfo<>(books);
    }

    @Override
    public void save(Book book) {
       book.setCategory(category(book.getCategories()));
       Date date=new Date();
        book.setCreatetime(date);
        bookMapper.save(book);
    }

    @Override
    public void delete(Integer id) {
    bookMapper.delete(id);
    }

    @Override
    public Book getById(Integer id) {
        Book book = bookMapper.getById(id);
        return book;
    }

    @Override
    public void update(Book book) {
        book.setCategory(category(book.getCategories()));
        Date date=new Date();
        book.setUpdatetime(date);
        bookMapper.update(book);
    }

    private String category(List<String> categories){
        StringBuilder sb=new StringBuilder();
        if (CollUtil.isNotEmpty(categories)){
            categories.forEach(v->sb.append(v).append(">"));
           return sb.substring(0,sb.lastIndexOf(">"));
        }
        return sb.toString();
    }
}
